import Taro from "@tarojs/taro";
import { CACHE_KEY } from '../service/config'
import { getCache,removeCache } from '../utils/cache'
import api from './api'

const tid = window.location.host.split('.')[0]


export function getJSON(data) {
  const { token } = getCache(CACHE_KEY)
  const params = {
    data,
    url: api.getUrl,
    method: 'GET',
    header: {
      'agent': tid,
      'content-type': 'application/json',
      'token':token ? token:""
    },
  }
 return requestData(params)
}

export function openGetJSON(data) {
  const params = {
    data,
    url: api.openUrl,
    method: 'GET',
    header: {
      'agent': tid,
      'content-type': 'application/json',
    },
  }
 return requestData(params)
}

export function postJSON(data) {
  const { token } = getCache(CACHE_KEY)
  const params = {
    data,
    url: api.postUrl,
    method: 'POST',
    header: {
      'agent': tid,
      'content-type': 'application/x-www-form-urlencoded',
      'token':token ? token:""
    },
  }
  return requestData(params)
}

export function uploadJSON(data) {
  const { token } = getCache(CACHE_KEY)
  const params = {
    data,
    url: api.uploadURL+"?folder=icon",
    method: 'POST',
    header: {
      'agent': tid,
      'token':token ? token:""
    },
  }
  return requestData(params)
}

const requestData = (params) => {
  let title = "";
  if (params.method === 'GET') {
    title = "玩命获取中...";
  } else {
    title = "请稍后...";
  }
  Taro.showLoading({
    title,
    mask:true
  });
  return Taro.request({
    ...params,
    mode: 'cors',
    success: function (data) {
      if (data.data.state === '503') {
        removeCache(CACHE_KEY)
        Taro.redirectTo({
          url:'/pages/mine/register?status=1'
        })
      }
      return false;
    }
  }).then(result => {
    Taro.hideLoading();
    return result;
  });
}

